/*
 * @Author: suxunying
 * @desc: store
 * @Date: 2021-07-20 17:37:48
 * @LastEditors: suxunying
 * @LastEditTime: 2021-07-26 10:24:12
 * @FilePath: \bmp-poc\micro\src\store\index.ts
 */
import Vue from 'vue';
import Vuex from 'vuex';
import SharedModule from '@/shared';

Vue.use(Vuex);

let shared:any = null;

export interface UserInfo {
    username: string,
}

interface State {
    locale: string,
    userinfo: UserInfo | Record<string, never>,
}

export default new Vuex.Store({
    state: {
        locale: '',
        userinfo: {},
    },
    mutations: {
        SET_LOCALE: (state: State, locale: string) => {
            state.locale = locale;
        },
        SET_USERINFO: (state: State, userinfo: UserInfo) => {
            state.userinfo = userinfo;
        },
    },
    actions: {
        initShared() {
            shared = SharedModule.getShared();
            // 通过 SharedModule.subscribe 传入回调函数进行订阅， 可以数组形式批量传入
            // 当pool内数据有变化时（监听到redux提供的set方法执行了），会通过回调函数统一发布
            this.dispatch('setLocale');
            this.dispatch('setUserinfo');
            SharedModule.subscribe([
                () => {
                    this.dispatch('setLocale');
                },
                () => {
                    this.dispatch('setUserinfo');
                },
            ]);
        },
        setLocale({ commit }) {
            const locale = shared.dispatch('locale/getLocale');
            commit('SET_LOCALE', locale);
        },
        setUserinfo({ commit }) {
            const userinfo = shared.dispatch('user/getUserinfo');
            commit('SET_USERINFO', userinfo);
        },
    },
    getters: {
        locale: (state: State) => state.locale,
        userinfo: (state: State) => state.userinfo,
    },
    modules: {
    },
});
